/**
 *
 */
package com.wedroid.r2d2.support.response.login;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lute
 *
 */
public class LoginStatusResponse extends AbstractLoginResponse {

    private static final String REGEX_CODE = "window.code=(\\d+);";

    private static final String REGEX_REDIRECT_URI = "window.redirect_uri=\"(\\S+?)\";";

    private String redirectURI;

    private String baseURI;

    private Pattern codePattern;

    private Pattern redirectURIPattern;

    /**
     *
     */
    public LoginStatusResponse() {
        this.codePattern = Pattern.compile(REGEX_CODE);
        this.redirectURIPattern = Pattern.compile(REGEX_REDIRECT_URI, Pattern.MULTILINE);
    }

    /* (non-Javadoc)
     * @see com.wedroid.r2d2.support.response.DroidResponse#parse(java.lang.String)
     */
    public void parse(String response) {
        // Find code first
        Matcher codeMather = codePattern.matcher(response);
        if (codeMather.find()) {

            int code = Integer.valueOf(codeMather.group(1));
            status = LoginStatus.codeOf(code);

            if (status.isSuccess()) {
                // If response is success, parse redirect URI
                Matcher redirectURIMatcher = redirectURIPattern.matcher(response);
                if (redirectURIMatcher.find()) {
                    try {
                        URI uri = new URI(redirectURIMatcher.group(1));
                        this.redirectURI = uri.toString();
                        StringBuilder originBuilder = new StringBuilder(uri.getScheme())
                                                                .append("://")
                                                                .append(uri.getHost());
                        int port = uri.getPort();
                        if (port != -1) {
                            originBuilder.append(":").append(port);
                        }
                        this.baseURI = originBuilder.toString();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * @return the redirectURI
     */
    public String getRedirectURI() {
        return redirectURI;
    }

    /**
     * @return the origin
     */
    public String getOrigin() {
        return baseURI;
    }

}
